package com.example.demo1.dao;

import com.example.demo1.Entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class userDao {
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    // 用户行映射器
    private static final class UserRowMapper implements RowMapper<User> {
        @Override
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user = new User();
            user.setId(rs.getLong("id"));
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            user.setName(rs.getString("name"));
            user.setAge(rs.getInt("age"));
            return user;
        }
    }
    
    // 获取所有用户
    public List<User> getAllUsers() {
        String sql = "SELECT * FROM users";
        return jdbcTemplate.query(sql, new UserRowMapper());
    }
    
    // 根据用户名获取用户
    public User getUserByUsername(String username) {
        String sql = "SELECT * FROM users WHERE username = ?";
        List<User> users = jdbcTemplate.query(sql, new UserRowMapper(), username);
        return users.isEmpty() ? null : users.get(0);
    }
    
    // 插入新用户
    public int insertUser(User user) {
        String sql = "INSERT INTO users (username, password, name, age) VALUES (?, ?, ?, ?)";
        return jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), user.getName(), user.getAge());
    }
    
    // 更新用户信息
    public int updateUser(User user) {
        String sql = "UPDATE users SET name = ?, age = ?, password = ? WHERE username = ?";
        return jdbcTemplate.update(sql, user.getName(), user.getAge(), user.getPassword(), user.getUsername());
    }
    
    // 删除用户
    public int deleteUser(String username) {
        String sql = "DELETE FROM users WHERE username = ?";
        return jdbcTemplate.update(sql, username);
    }
    
    // 检查用户名是否存在
    public boolean checkUsernameExists(String username) {
        String sql = "SELECT COUNT(*) FROM users WHERE username = ?";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class, username);
        return count != null && count > 0;
    }
}
